<template>
    <!-- 展示所有仓库产品以及库存 -->
    <div v-if="dataset.body.length !== 0" class="inventory-container">
        <VueUiTable :dataset="dataset" :config="config"></VueUiTable>
    </div>
    <div v-if="dataset.body.length == 0" class="inventory-container">
        <el-empty description="仓库或产品没有数据" />
    </div>
</template>

<script setup lang="ts">
import { getAllCustomerList } from '@/api/customer';
import { getAllProductList } from '@/api/product';
import { getAllWarehouseList } from '@/api/warehouse';
import { useSystemStore } from '@/store/modules/system';
import { VueUiTable, VueUiTableDataset, VueUiTableConfig } from 'vue-data-ui';

onMounted(async () => {
    // 获取所有客户列表
    const originCustomerList = await getAllCustomerList();
    // 判断是否有客户数据
    if (originCustomerList.data.length <= 0) {
        ElMessage.warning('暂无客户数据');
        return;
    }
    originCustomerList.data.forEach((item: any) => {
        customerList.push(item);
    });

    // 组件挂载时，加载产品数据
    const originProductList = await getAllProductList();
    // 判断是否有产品数据
    if (originProductList.data.length <= 0) {
        ElMessage.warning('暂无产品数据');
        return;
    }

    // 获取所有仓库的信息
    const originWarehouseList = await getAllWarehouseList();
    // 判断是否有仓库数据
    if (originWarehouseList.data.length <= 0) {
        ElMessage.warning('暂无仓库数据');
        return;
    }
    originWarehouseList.data.forEach((item: any) => {
        warehouseList.push(item);
    });

    // 组装表格数据，遍历所有产品列表，获取每个产品的信息
    for (let index = 0; index < originProductList.data.length; index++) {
        const products = originProductList.data[index];
        // 遍历每个产品的库存信息
        for (let index = 0; index < products.products.length; index++) {
            const product = products.products[index];
            // 查找仓库位置
            const warehouse = warehouseList.find((item) => item.info.find((i) => i.productId == product._id));
            // 数据对象
            const obj = {
                abbreviation: matchCustomerAbbreviation(products.customerId),
                productName: product.productName,
                productSize: product.productSize,
                stock: product.stock,
            };
            // 如果有仓库位置，就添加仓库位置
            if (warehouse) {
                obj['warehouseLocation'] = '仓库：' + warehouse.location + '区 ' + warehouse.abscissa + '-' + warehouse.ordinate;
            } else {
                obj['warehouseLocation'] = '无库存';
            }
            // 填充数据
            productList.push(obj);
        }
    }

    productList.forEach((item) => {
        dataset.body.push({
            td: Object.values(item),
        });
    });

    // 设置表格的最大高度
    const inventoryContainer = document.querySelector('.inventory-container');
    const inventoryContainerHeight = inventoryContainer!.clientHeight - 100 || 0;
    config.maxHeight = inventoryContainerHeight;
});

// 窗口大小改变时，重新计算表格高度
window.addEventListener('resize', () => {
    const inventoryContainer = document.querySelector('.inventory-container');
    const inventoryContainerHeight = inventoryContainer!.clientHeight - 100 || 0;
    config.maxHeight = inventoryContainerHeight;
});

// 取消窗口大小改变时，重新计算表格高度
onUnmounted(() => {
    window.removeEventListener('resize', () => {});
});

/* ***********************************通用属性*********************************** */
// 所有产品列表
const productList = reactive<any>([]);
// 所有仓库列表
const warehouseList = reactive<AjaxResponse['warehouseList']>([]);
// 所有客户列表
const customerList = reactive<AjaxResponse['customerList']>([]);
// 匹配客户简称
const matchCustomerAbbreviation = (customerId: string) => {
    return customerList.find((item) => item._id == customerId)?.customerAbbreviation || '未知客户';
};

// vue-data-ui 表格数据
const dataset = reactive<VueUiTableDataset>({
    header: [
        // 客户简称
        {
            name: '客户简称',
            type: 'text',
            average: false,
            decimals: undefined,
            sum: false,
            isSort: true,
            isSearch: true,
            isMultiselect: true,
            isPercentage: false,
            percentageTo: undefined,
            suffix: '',
            prefix: '',
            rangeFilter: false,
        },
        // 产品名称
        {
            name: '产品名称',
            type: 'text',
            average: false,
            decimals: undefined,
            sum: false,
            isSort: true,
            isSearch: true,
            isMultiselect: false,
            isPercentage: false,
            percentageTo: undefined,
            suffix: '',
            prefix: '',
            rangeFilter: false,
        },
        // 产品尺寸
        {
            name: '产品尺寸',
            type: 'text',
            average: false,
            decimals: undefined,
            sum: false,
            isSort: true,
            isSearch: true,
            isMultiselect: false,
            isPercentage: false,
            percentageTo: undefined,
            suffix: '',
            prefix: '',
            rangeFilter: false,
        },
        // 库存
        {
            name: '库存',
            type: 'numeric',
            average: false,
            decimals: undefined,
            sum: true,
            isSort: true,
            isSearch: false,
            isMultiselect: false,
            isPercentage: false,
            percentageTo: undefined,
            suffix: '',
            prefix: '',
            rangeFilter: false,
        },
        // 仓库位置
        {
            name: '仓库位置',
            type: 'text',
            average: false,
            decimals: undefined,
            sum: false,
            isSort: false,
            isSearch: false,
            isMultiselect: false,
            isPercentage: false,
            percentageTo: undefined,
            suffix: '',
            prefix: '',
            rangeFilter: false,
        },
    ],
    body: [],
});
// vue-data-ui 表格配置
const config = reactive<VueUiTableConfig>({
    fontFamily: 'inherit',
    rowsPerPage: 25,
    style: {
        th: {
            backgroundColor: '#F3F4F6',
            color: '#1A1A1A',
            outline: '1px solid #C4C4C4',
            selected: { backgroundColor: '#42d392', color: '#1a1a1a' },
        },
        rows: {
            even: {
                backgroundColor: '#F3F4F6',
                color: '#1A1A1A',
                selectedCell: { backgroundColor: '#5de8aa', color: '#2D353C' },
                selectedNeighbors: { backgroundColor: '#b2d4c4', color: '#1A1A1A' },
            },
            odd: {
                backgroundColor: '#e1e5e8',
                color: '#1A1A1A',
                selectedCell: { backgroundColor: '#42d392', color: '#2D353C' },
                selectedNeighbors: { backgroundColor: '#9cbaac', color: '#1A1A1A' },
            },
        },
        inputs: { backgroundColor: '#FFFFFF', color: '#1A1A1A', border: '1px solid #C4C4C4', accentColor: '#42d392' },
        dropdowns: {
            backgroundColor: '#FFFFFF',
            color: '#1A1A1A',
            icons: { selected: { color: '#42d392', unicode: '✔' }, unselected: { color: '#ff6400', unicode: '✖' } },
        },
        infoBar: { backgroundColor: '#e1e5e8', color: '#1A1A1A' },
        pagination: {
            buttons: { backgroundColor: '#e1e5e8', color: '#1A1A1A', opacityDisabled: '0.3' },
            navigationIndicator: { backgroundColor: '#42d392' },
        },
        exportMenu: { backgroundColor: '#FFFFFF', color: '#1A1A1A', buttons: { backgroundColor: '#e1e5e8', color: '#2D353C' } },
        closeButtons: { backgroundColor: 'transparent', color: '#ff6400', borderRadius: '50%' },
        chart: {
            modal: {
                backgroundColor: '#FFFFFF',
                color: '#1A1A1A',
                buttons: {
                    selected: { backgroundColor: '#42d392', color: '#FFFFFF' },
                    unselected: { backgroundColor: '#e1e5e8', color: '#1A1A1A' },
                },
            },
            layout: {
                backgroundColor: '#FFFFFF',
                axis: { stroke: '#ccd1d4', strokeWidth: 2 },
                bar: { fill: '#42d392', stroke: '#FFFFFF' },
                line: {
                    stroke: '#42d392',
                    strokeWidth: 4,
                    plot: { fill: '#5fe3a8', stroke: '#FFFFFF', strokeWidth: 1, radius: { selected: 6, unselected: 4 } },
                    selector: { stroke: '#ff6400', strokeWidth: 1, strokeDasharray: 5 },
                },
                labels: { color: '#1A1A1A' },
                progression: { stroke: '#565656', strokeWidth: 2, strokeDasharray: 4, arrowSize: 7 },
            },
        },
    },
    translations: {
        average: '平均',
        by: 'by',
        chooseCategoryColumn: '选择类别列',
        exportAllButton: 'CSV all',
        exportAllLabel: '导出当前筛选数据集的数据',
        exportPageButton: 'CSV page',
        exportPageLabel: '导出当前页面的数据',
        from: 'From',
        inputPlaceholder: '搜索...',
        makeDonut: '生成圆环图',
        nb: '个数',
        page: '页码',
        paginatorLabel: '每页个数',
        sizeWarning: '一次显示太多行可能会导致性能下降',
        sum: '求和',
        to: 'To',
        total: '总共',
        totalRows: '总个数',
    },
    useChart: true,
});

// 系统配置
const useSystem = useSystemStore();
// 计算宽度
const inventoryWidth = computed(() => {
    return useSystem.config.isCollapse ? 'calc(100vw - 84px)' : 'calc(100vw - 220px)';
});
</script>

<style scoped lang="scss">
.inventory-container {
    width: v-bind(inventoryWidth);
    height: calc(100vh - 80px);
}
</style>
